/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.lanchat.model.net;

import com.lanchat.model.data.ChatMessage;
import com.lanchat.model.data.User;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * 用于接收信息的类
 * 
 * @author Zhangyiheng
 */
public class UdpRecv {

    private DatagramSocket ds;
    private DatagramPacket dp;
    private Thread thread;
    private boolean running = true;

    public UdpRecv() {
        try {
            ds = new DatagramSocket(NetConstant.UDPCHATPORT);
        } catch (SocketException ex) {
            Logger.getLogger(UdpRecv.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    public Object run() {
        Object obj=null;
        if(!ds.isClosed()){
            ObjectInputStream in = null;
            try {
                byte[] buffer=new byte[NetConstant.DATAGRAMPACKET_SIZE];
                dp=new DatagramPacket(buffer, buffer.length);
                ds.receive(dp);
                in=new ObjectInputStream(new ByteArrayInputStream(buffer));
                obj=in.readObject();
                in.close();
            } catch (Exception ex) {
                Logger.getLogger(UdpRecv.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return obj;
    }


    public void Stop(){
        running=false;
        ds.close();
    }
}
